package thread;


import javax.jws.Oneway;
import java.util.PriorityQueue;

// 通过这个类, 描述了一个任务
class MyTimeTask implements Comparable<MyTimeTask>{
    private Runnable runnable;

    private long time;
    public MyTimeTask(Runnable runnable, long delay) {
        this.runnable = runnable;
        time = System.currentTimeMillis() + delay;
    }

    public long getTime() {
        return time;
    }

    public Runnable getRunnable() {
        return runnable;
    }

    @Override
    public int compareTo(MyTimeTask o) {
        return (int) (this.time - o.time);
    }
}
// 咱们自己搞的定时器
class MyTimer {
    // 使用一个数据结构, 保存所有要安排的任务.
    private PriorityQueue<MyTimeTask> queue = new PriorityQueue<>();
    private final Object locker = new Object();

    public void schedule(Runnable runnable, long delay) {
        synchronized (locker) {
            queue.offer(new MyTimeTask(runnable, delay));
            locker.notify();
        }
    }

    // 搞个扫描线程.
    public MyTimer() {
        Thread t = new Thread(() -> {
            // 扫描线程, 需要不停的扫描队首元素, 看是否是到达时间.
            while (true) {
                try {
                        synchronized (locker) {
                            while (queue.isEmpty()) {
                                locker.wait();
                            }
                            MyTimeTask task = queue.peek();
                            long curTime = System.currentTimeMillis();
                            if (task.getTime() <= curTime) {
                                task.getRunnable().run();
                                queue.poll();
                            } else {
                                locker.wait(task.getTime() - curTime);
                            }
                        }

                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }

        });
        t.start();
    }
}
// 实现定时器
public class demo6 {
    public static void main(String[] args) {
        MyTimer myTimer = new MyTimer();
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("3000");
            }
        }, 3000);

        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("2000");
            }
        }, 2000);

        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("1000");
            }
        }, 1000);
        System.out.println("程序开始执行");


    }
}
